#!/bin/bash
#
# Script to be placed in one of
#   /etc/cron.daily
#   /etc/cron.weekly
#
# or called directly via /etc/crontab
#
# Do NOT rename it so it has a dot "." in the name, this will cause
# ubuntu (and perhaps other distros) to ignore it.
#
# CONF    is used to point out a configuration file (optional)
# SCRIPT  points out where to find plexupdate.sh
# LOGGING if true, logs all output to syslog daemon facility
#         (typically /var/log/daemon.log or /var/log/syslog)
#

if [ ! -f /etc/plexupdate.cron.conf ]; then
	echo "ERROR: You have not configured /etc/plexupdate.cron.conf" >&2
	exit 255
else
	source /etc/plexupdate.cron.conf
fi

if [ -z "${SCRIPT}" -o ! -f "${SCRIPT}" ]; then
	echo "ERROR: Cannot find plexupdate.sh (tried ${SCRIPT})" >&2
	exit 255
elif [ ${EUID} -eq 0 ]; then
	UNSAFE_FILES=$(find -L "$(dirname "${SCRIPT}")" -perm /002 -or -not -uid 0 -or -not -gid 0)
	if [ ! -z "${UNSAFE_FILES}" ]; then
		echo "ERROR: Permissions on some files are too lax for running as root. Files must be owned by root:root and not world-writeable." >&2
		echo "Unsafe files found:" >&2
		echo "${UNSAFE_FILES}" >&2
		exit 255
	fi
fi

if [ ! -z "$CONF" ]; then
	# We have a config file, prefix it with parameter
	if [ ! -f "${CONF}" ]; then
		echo "ERROR: Cannot find config file (tried ${CONF})" >&2
		exit 255
	fi
	CONF="--config=${CONF}"
fi

LOGFILE=$(mktemp /tmp/plexupdate.cron.XXXX)

RET=0
if $LOGGING; then
	"${SCRIPT}" "${CONF}" 2>&1 | tee ${LOGFILE} | logger -t plexupdate -p daemon.info
	RET="${PIPESTATUS[0]}"
else
	"${SCRIPT}" "${CONF}" >${LOGFILE} 2>&1
	RET=$?
fi

if [ $RET -ne 0 ] ; then
	# Make sure user gets an email about this (when not success or if user has specified when)
	cat ${LOGFILE} >&2

	# Output will produce a cron email, so we can reset the exit status
	if [ $RET -eq 10 ]; then
		RET=0
	fi
fi

rm "${LOGFILE}" 2>/dev/null
exit $RET
